package com.datagateway.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 数据统计管理器
 * 负责收集、统计和分析系统运行数据，生成各种统计报表
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@Component
public class DataStatisticsManager {

    private static final Logger logger = LoggerFactory.getLogger(DataStatisticsManager.class);

    @Autowired
    private AlertManager alertManager;

    @Autowired
    private SystemMonitor systemMonitor;

    /**
     * 统计数据收集
     */
    private final AtomicLong totalProcessedMessages = new AtomicLong(0);
    private final AtomicLong totalSuccessfulMessages = new AtomicLong(0);
    private final AtomicLong totalFailedMessages = new AtomicLong(0);
    private final AtomicLong totalRetriedMessages = new AtomicLong(0);
    private final AtomicLong totalDataSize = new AtomicLong(0);
    private final AtomicLong totalProcessingTime = new AtomicLong(0);

    /**
     * 时间窗口统计
     */
    private final Map<String, TimeWindowStatistics> timeWindowStats = new ConcurrentHashMap<>();
    private final Map<String, BusinessStatistics> businessStats = new ConcurrentHashMap<>();
    private final Map<String, PerformanceStatistics> performanceStats = new ConcurrentHashMap<>();

    /**
     * 统计配置
     */
    private boolean statisticsEnabled = true;
    private int timeWindowSizeMinutes = 5;
    private int maxTimeWindows = 288; // 24小时
    private int reportGenerationIntervalMinutes = 60;
    private int dataRetentionDays = 30;

    /**
     * 执行器
     */
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2, r -> {
        Thread t = new Thread(r, "data-statistics-scheduler");
        t.setDaemon(true);
        return t;
    });

    /**
     * 统计缓存
     */
    private final AtomicReference<SystemStatistics> cachedSystemStats = new AtomicReference<>();
    private final AtomicReference<Long> lastCacheTime = new AtomicReference<>(0L);
    private final long cacheExpirationMs = 60000; // 1分钟

    /**
     * 初始化数据统计管理器
     */
    public void initialize() {
        try {
            // 启动统计清理任务
            startStatisticsCleanupTask();
            
            // 启动报表生成任务
            startReportGenerationTask();
            
            logger.info("数据统计管理器初始化成功");
            
        } catch (Exception e) {
            logger.error("数据统计管理器初始化失败", e);
            alertManager.sendSystemErrorAlert("数据统计管理器初始化失败", e.getMessage());
        }
    }

    /**
     * 停止数据统计管理器
     */
    public void stop() {
        try {
            scheduler.shutdown();
            if (!scheduler.awaitTermination(30, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
            
            logger.info("数据统计管理器停止成功");
            
        } catch (Exception e) {
            logger.error("数据统计管理器停止失败", e);
        }
    }

    /**
     * 记录消息处理统计
     * 
     * @param messageId 消息ID
     * @param success 是否成功
     * @param dataSize 数据大小
     * @param processingTime 处理时间
     * @param businessType 业务类型
     * @param retryCount 重试次数
     */
    public void recordMessageProcessing(String messageId, boolean success, long dataSize, 
                                      long processingTime, String businessType, int retryCount) {
        if (!statisticsEnabled) {
            return;
        }

        try {
            // 更新全局统计
            totalProcessedMessages.incrementAndGet();
            totalDataSize.addAndGet(dataSize);
            totalProcessingTime.addAndGet(processingTime);
            
            if (success) {
                totalSuccessfulMessages.incrementAndGet();
            } else {
                totalFailedMessages.incrementAndGet();
            }
            
            if (retryCount > 0) {
                totalRetriedMessages.addAndGet(retryCount);
            }
            
            // 更新时间窗口统计
            updateTimeWindowStatistics(success, dataSize, processingTime, businessType);
            
            // 更新业务统计
            updateBusinessStatistics(businessType, success, dataSize, processingTime);
            
            // 更新性能统计
            updatePerformanceStatistics(processingTime, dataSize);
            
            // 清除缓存
            clearCache();
            
        } catch (Exception e) {
            logger.error("记录消息处理统计失败: {}", messageId, e);
        }
    }

    /**
     * 获取系统统计信息
     * 
     * @return 系统统计信息
     */
    public SystemStatistics getSystemStatistics() {
        try {
            // 检查缓存
            SystemStatistics cached = getCachedSystemStatistics();
            if (cached != null) {
                return cached;
            }
            
            // 生成新的统计信息
            SystemStatistics stats = generateSystemStatistics();
            
            // 更新缓存
            cachedSystemStats.set(stats);
            lastCacheTime.set(System.currentTimeMillis());
            
            return stats;
            
        } catch (Exception e) {
            logger.error("获取系统统计信息失败", e);
            return new SystemStatistics();
        }
    }

    /**
     * 获取时间窗口统计
     * 
     * @param timeWindow 时间窗口（分钟）
     * @return 时间窗口统计
     */
    public List<TimeWindowStatistics> getTimeWindowStatistics(int timeWindow) {
        try {
            List<TimeWindowStatistics> result = new ArrayList<>();
            long currentTime = System.currentTimeMillis();
            long windowSizeMs = timeWindow * 60 * 1000;
            
            for (Map.Entry<String, TimeWindowStatistics> entry : timeWindowStats.entrySet()) {
                TimeWindowStatistics stats = entry.getValue();
                if (currentTime - stats.getStartTime() <= windowSizeMs) {
                    result.add(stats);
                }
            }
            
            // 按时间排序
            result.sort(Comparator.comparing(TimeWindowStatistics::getStartTime));
            
            return result;
            
        } catch (Exception e) {
            logger.error("获取时间窗口统计失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取业务统计
     * 
     * @return 业务统计列表
     */
    public List<BusinessStatistics> getBusinessStatistics() {
        try {
            return new ArrayList<>(businessStats.values());
        } catch (Exception e) {
            logger.error("获取业务统计失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取性能统计
     * 
     * @return 性能统计
     */
    public PerformanceStatistics getPerformanceStatistics() {
        try {
            return performanceStats.values().stream()
                .reduce(new PerformanceStatistics(), this::mergePerformanceStatistics);
        } catch (Exception e) {
            logger.error("获取性能统计失败", e);
            return new PerformanceStatistics();
        }
    }

    /**
     * 生成日报表
     * 
     * @param date 日期
     * @return 日报表
     */
    public DailyReport generateDailyReport(Date date) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            
            long startTime = calendar.getTimeInMillis();
            long endTime = startTime + 24 * 60 * 60 * 1000;
            
            // 收集当天的统计数据
            long dailyProcessed = 0;
            long dailySuccessful = 0;
            long dailyFailed = 0;
            long dailyDataSize = 0;
            long dailyProcessingTime = 0;
            
            for (TimeWindowStatistics stats : timeWindowStats.values()) {
                if (stats.getStartTime() >= startTime && stats.getStartTime() < endTime) {
                    dailyProcessed += stats.getProcessedCount();
                    dailySuccessful += stats.getSuccessfulCount();
                    dailyFailed += stats.getFailedCount();
                    dailyDataSize += stats.getTotalDataSize();
                    dailyProcessingTime += stats.getTotalProcessingTime();
                }
            }
            
            return new DailyReport(
                date,
                dailyProcessed,
                dailySuccessful,
                dailyFailed,
                dailyDataSize,
                dailyProcessingTime,
                System.currentTimeMillis()
            );
            
        } catch (Exception e) {
            logger.error("生成日报表失败: {}", date, e);
            return new DailyReport(date, 0, 0, 0, 0, 0, System.currentTimeMillis());
        }
    }

    /**
     * 生成周报表
     * 
     * @param weekStartDate 周开始日期
     * @return 周报表
     */
    public WeeklyReport generateWeeklyReport(Date weekStartDate) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(weekStartDate);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            
            long startTime = calendar.getTimeInMillis();
            long endTime = startTime + 7 * 24 * 60 * 60 * 1000;
            
            // 收集一周的统计数据
            long weeklyProcessed = 0;
            long weeklySuccessful = 0;
            long weeklyFailed = 0;
            long weeklyDataSize = 0;
            long weeklyProcessingTime = 0;
            
            for (TimeWindowStatistics stats : timeWindowStats.values()) {
                if (stats.getStartTime() >= startTime && stats.getStartTime() < endTime) {
                    weeklyProcessed += stats.getProcessedCount();
                    weeklySuccessful += stats.getSuccessfulCount();
                    weeklyFailed += stats.getFailedCount();
                    weeklyDataSize += stats.getTotalDataSize();
                    weeklyProcessingTime += stats.getTotalProcessingTime();
                }
            }
            
            return new WeeklyReport(
                weekStartDate,
                weeklyProcessed,
                weeklySuccessful,
                weeklyFailed,
                weeklyDataSize,
                weeklyProcessingTime,
                System.currentTimeMillis()
            );
            
        } catch (Exception e) {
            logger.error("生成周报表失败: {}", weekStartDate, e);
            return new WeeklyReport(weekStartDate, 0, 0, 0, 0, 0, System.currentTimeMillis());
        }
    }

    /**
     * 生成月报表
     * 
     * @param month 月份
     * @return 月报表
     */
    public MonthlyReport generateMonthlyReport(Date month) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(month);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            
            long startTime = calendar.getTimeInMillis();
            calendar.add(Calendar.MONTH, 1);
            long endTime = calendar.getTimeInMillis();
            
            // 收集一个月的统计数据
            long monthlyProcessed = 0;
            long monthlySuccessful = 0;
            long monthlyFailed = 0;
            long monthlyDataSize = 0;
            long monthlyProcessingTime = 0;
            
            for (TimeWindowStatistics stats : timeWindowStats.values()) {
                if (stats.getStartTime() >= startTime && stats.getStartTime() < endTime) {
                    monthlyProcessed += stats.getProcessedCount();
                    monthlySuccessful += stats.getSuccessfulCount();
                    monthlyFailed += stats.getFailedCount();
                    monthlyDataSize += stats.getTotalDataSize();
                    monthlyProcessingTime += stats.getTotalProcessingTime();
                }
            }
            
            return new MonthlyReport(
                month,
                monthlyProcessed,
                monthlySuccessful,
                monthlyFailed,
                monthlyDataSize,
                monthlyProcessingTime,
                System.currentTimeMillis()
            );
            
        } catch (Exception e) {
            logger.error("生成月报表失败: {}", month, e);
            return new MonthlyReport(month, 0, 0, 0, 0, 0, System.currentTimeMillis());
        }
    }

    /**
     * 获取统计配置
     * 
     * @return 统计配置
     */
    public StatisticsConfiguration getConfiguration() {
        return new StatisticsConfiguration(
            statisticsEnabled,
            timeWindowSizeMinutes,
            maxTimeWindows,
            reportGenerationIntervalMinutes,
            dataRetentionDays,
            System.currentTimeMillis()
        );
    }

    /**
     * 设置统计配置
     * 
     * @param enabled 是否启用统计
     * @param timeWindowSize 时间窗口大小
     * @param maxTimeWindows 最大时间窗口数
     * @param reportInterval 报表生成间隔
     * @param retentionDays 数据保留天数
     */
    public void setConfiguration(boolean enabled, int timeWindowSize, int maxTimeWindows,
                               int reportInterval, int retentionDays) {
        this.statisticsEnabled = enabled;
        this.timeWindowSizeMinutes = timeWindowSize;
        this.maxTimeWindows = maxTimeWindows;
        this.reportGenerationIntervalMinutes = reportInterval;
        this.dataRetentionDays = retentionDays;
        
        logger.info("数据统计配置已更新: 启用={}, 时间窗口={}, 最大窗口={}, 报表间隔={}, 保留天数={}", 
                   enabled, timeWindowSize, maxTimeWindows, reportInterval, retentionDays);
    }

    /**
     * 更新时间窗口统计
     */
    private void updateTimeWindowStatistics(boolean success, long dataSize, long processingTime, String businessType) {
        try {
            long currentTime = System.currentTimeMillis();
            long windowStart = (currentTime / (timeWindowSizeMinutes * 60 * 1000)) * (timeWindowSizeMinutes * 60 * 1000);
            String windowKey = String.valueOf(windowStart);
            
            TimeWindowStatistics stats = timeWindowStats.computeIfAbsent(windowKey, 
                k -> new TimeWindowStatistics(windowStart, timeWindowSizeMinutes * 60 * 1000));
            
            stats.incrementProcessed();
            stats.addDataSize(dataSize);
            stats.addProcessingTime(processingTime);
            
            if (success) {
                stats.incrementSuccessful();
            } else {
                stats.incrementFailed();
            }
            
        } catch (Exception e) {
            logger.error("更新时间窗口统计失败", e);
        }
    }

    /**
     * 更新业务统计
     */
    private void updateBusinessStatistics(String businessType, boolean success, long dataSize, long processingTime) {
        try {
            BusinessStatistics stats = businessStats.computeIfAbsent(businessType, 
                BusinessStatistics::new);
            
            stats.incrementProcessed();
            stats.addDataSize(dataSize);
            stats.addProcessingTime(processingTime);
            
            if (success) {
                stats.incrementSuccessful();
            } else {
                stats.incrementFailed();
            }
            
        } catch (Exception e) {
            logger.error("更新业务统计失败", e);
        }
    }

    /**
     * 更新性能统计
     */
    private void updatePerformanceStatistics(long processingTime, long dataSize) {
        try {
            String key = "global";
            PerformanceStatistics stats = performanceStats.computeIfAbsent(key, 
                k -> new PerformanceStatistics());
            
            stats.addProcessingTime(processingTime);
            stats.addDataSize(dataSize);
            stats.updateMinMaxTimes(processingTime);
            
        } catch (Exception e) {
            logger.error("更新性能统计失败", e);
        }
    }

    /**
     * 生成系统统计信息
     */
    private SystemStatistics generateSystemStatistics() {
        long total = totalProcessedMessages.get();
        long successful = totalSuccessfulMessages.get();
        long failed = totalFailedMessages.get();
        long retried = totalRetriedMessages.get();
        long dataSize = totalDataSize.get();
        long processingTime = totalProcessingTime.get();
        
        return new SystemStatistics(
            total,
            successful,
            failed,
            retried,
            dataSize,
            processingTime,
            timeWindowStats.size(),
            businessStats.size(),
            statisticsEnabled,
            System.currentTimeMillis()
        );
    }

    /**
     * 获取缓存的系统统计信息
     */
    private SystemStatistics getCachedSystemStatistics() {
        Long cacheTime = lastCacheTime.get();
        if (cacheTime != null && System.currentTimeMillis() - cacheTime < cacheExpirationMs) {
            return cachedSystemStats.get();
        }
        return null;
    }

    /**
     * 清除缓存
     */
    private void clearCache() {
        cachedSystemStats.set(null);
        lastCacheTime.set(0L);
    }

    /**
     * 合并性能统计
     */
    private PerformanceStatistics mergePerformanceStatistics(PerformanceStatistics stats1, PerformanceStatistics stats2) {
        PerformanceStatistics merged = new PerformanceStatistics();
        merged.setTotalProcessingTime(stats1.getTotalProcessingTime() + stats2.getTotalProcessingTime());
        merged.setTotalDataSize(stats1.getTotalDataSize() + stats2.getTotalDataSize());
        merged.setMinProcessingTime(Math.min(stats1.getMinProcessingTime(), stats2.getMinProcessingTime()));
        merged.setMaxProcessingTime(Math.max(stats1.getMaxProcessingTime(), stats2.getMaxProcessingTime()));
        merged.setCount(stats1.getCount() + stats2.getCount());
        return merged;
    }

    /**
     * 启动统计清理任务
     */
    private void startStatisticsCleanupTask() {
        scheduler.scheduleAtFixedRate(this::cleanupExpiredStatistics, 
            60, 60, TimeUnit.MINUTES);
    }

    /**
     * 启动报表生成任务
     */
    private void startReportGenerationTask() {
        scheduler.scheduleAtFixedRate(this::generateScheduledReports, 
            0, reportGenerationIntervalMinutes, TimeUnit.MINUTES);
    }

    /**
     * 清理过期统计
     */
    private void cleanupExpiredStatistics() {
        try {
            long currentTime = System.currentTimeMillis();
            long retentionTime = dataRetentionDays * 24 * 60 * 60 * 1000;
            
            List<String> expiredKeys = new ArrayList<>();
            for (Map.Entry<String, TimeWindowStatistics> entry : timeWindowStats.entrySet()) {
                if (currentTime - entry.getValue().getStartTime() > retentionTime) {
                    expiredKeys.add(entry.getKey());
                }
            }
            
            for (String key : expiredKeys) {
                timeWindowStats.remove(key);
            }
            
            logger.info("清理过期统计数据: {} 个时间窗口", expiredKeys.size());
            
        } catch (Exception e) {
            logger.error("清理过期统计失败", e);
        }
    }

    /**
     * 生成定时报表
     */
    private void generateScheduledReports() {
        try {
            // 这里可以实现定时报表生成逻辑
            // 例如：发送日报表邮件、生成报表文件等
            logger.debug("生成定时报表");
            
        } catch (Exception e) {
            logger.error("生成定时报表失败", e);
        }
    }

    /**
     * 系统统计信息类
     */
    public static class SystemStatistics {
        private final long totalProcessed;
        private final long totalSuccessful;
        private final long totalFailed;
        private final long totalRetried;
        private final long totalDataSize;
        private final long totalProcessingTime;
        private final int timeWindowCount;
        private final int businessTypeCount;
        private final boolean statisticsEnabled;
        private final long timestamp;

        public SystemStatistics() {
            this(0, 0, 0, 0, 0, 0, 0, 0, false, System.currentTimeMillis());
        }

        public SystemStatistics(long totalProcessed, long totalSuccessful, long totalFailed,
                              long totalRetried, long totalDataSize, long totalProcessingTime,
                              int timeWindowCount, int businessTypeCount, boolean statisticsEnabled, long timestamp) {
            this.totalProcessed = totalProcessed;
            this.totalSuccessful = totalSuccessful;
            this.totalFailed = totalFailed;
            this.totalRetried = totalRetried;
            this.totalDataSize = totalDataSize;
            this.totalProcessingTime = totalProcessingTime;
            this.timeWindowCount = timeWindowCount;
            this.businessTypeCount = businessTypeCount;
            this.statisticsEnabled = statisticsEnabled;
            this.timestamp = timestamp;
        }

        // Getter方法
        public long getTotalProcessed() { return totalProcessed; }
        public long getTotalSuccessful() { return totalSuccessful; }
        public long getTotalFailed() { return totalFailed; }
        public long getTotalRetried() { return totalRetried; }
        public long getTotalDataSize() { return totalDataSize; }
        public long getTotalProcessingTime() { return totalProcessingTime; }
        public int getTimeWindowCount() { return timeWindowCount; }
        public int getBusinessTypeCount() { return businessTypeCount; }
        public boolean isStatisticsEnabled() { return statisticsEnabled; }
        public long getTimestamp() { return timestamp; }
        
        public double getSuccessRate() {
            return totalProcessed > 0 ? (double) totalSuccessful / totalProcessed : 0.0;
        }
        
        public double getFailureRate() {
            return totalProcessed > 0 ? (double) totalFailed / totalProcessed : 0.0;
        }
        
        public double getAverageProcessingTime() {
            return totalProcessed > 0 ? (double) totalProcessingTime / totalProcessed : 0.0;
        }
        
        public double getAverageDataSize() {
            return totalProcessed > 0 ? (double) totalDataSize / totalProcessed : 0.0;
        }
    }

    /**
     * 时间窗口统计类
     */
    public static class TimeWindowStatistics {
        private final long startTime;
        private final long windowSize;
        private long processedCount;
        private long successfulCount;
        private long failedCount;
        private long totalDataSize;
        private long totalProcessingTime;

        public TimeWindowStatistics(long startTime, long windowSize) {
            this.startTime = startTime;
            this.windowSize = windowSize;
        }

        // Getter和Setter方法
        public long getStartTime() { return startTime; }
        public long getWindowSize() { return windowSize; }
        public long getProcessedCount() { return processedCount; }
        public void incrementProcessed() { this.processedCount++; }
        public long getSuccessfulCount() { return successfulCount; }
        public void incrementSuccessful() { this.successfulCount++; }
        public long getFailedCount() { return failedCount; }
        public void incrementFailed() { this.failedCount++; }
        public long getTotalDataSize() { return totalDataSize; }
        public void addDataSize(long dataSize) { this.totalDataSize += dataSize; }
        public long getTotalProcessingTime() { return totalProcessingTime; }
        public void addProcessingTime(long processingTime) { this.totalProcessingTime += processingTime; }
        
        public double getSuccessRate() {
            return processedCount > 0 ? (double) successfulCount / processedCount : 0.0;
        }
        
        public double getAverageProcessingTime() {
            return processedCount > 0 ? (double) totalProcessingTime / processedCount : 0.0;
        }
    }

    /**
     * 业务统计类
     */
    public static class BusinessStatistics {
        private final String businessType;
        private long processedCount;
        private long successfulCount;
        private long failedCount;
        private long totalDataSize;
        private long totalProcessingTime;

        public BusinessStatistics(String businessType) {
            this.businessType = businessType;
        }

        // Getter和Setter方法
        public String getBusinessType() { return businessType; }
        public long getProcessedCount() { return processedCount; }
        public void incrementProcessed() { this.processedCount++; }
        public long getSuccessfulCount() { return successfulCount; }
        public void incrementSuccessful() { this.successfulCount++; }
        public long getFailedCount() { return failedCount; }
        public void incrementFailed() { this.failedCount++; }
        public long getTotalDataSize() { return totalDataSize; }
        public void addDataSize(long dataSize) { this.totalDataSize += dataSize; }
        public long getTotalProcessingTime() { return totalProcessingTime; }
        public void addProcessingTime(long processingTime) { this.totalProcessingTime += processingTime; }
        
        public double getSuccessRate() {
            return processedCount > 0 ? (double) successfulCount / processedCount : 0.0;
        }
        
        public double getAverageProcessingTime() {
            return processedCount > 0 ? (double) totalProcessingTime / processedCount : 0.0;
        }
    }

    /**
     * 性能统计类
     */
    public static class PerformanceStatistics {
        private long totalProcessingTime;
        private long totalDataSize;
        private long minProcessingTime = Long.MAX_VALUE;
        private long maxProcessingTime = 0;
        private long count;

        public PerformanceStatistics() {}

        // Getter和Setter方法
        public long getTotalProcessingTime() { return totalProcessingTime; }
        public void setTotalProcessingTime(long totalProcessingTime) { this.totalProcessingTime = totalProcessingTime; }
        public void addProcessingTime(long processingTime) { this.totalProcessingTime += processingTime; }
        public long getTotalDataSize() { return totalDataSize; }
        public void setTotalDataSize(long totalDataSize) { this.totalDataSize = totalDataSize; }
        public void addDataSize(long dataSize) { this.totalDataSize += dataSize; }
        public long getMinProcessingTime() { return minProcessingTime == Long.MAX_VALUE ? 0 : minProcessingTime; }
        public void setMinProcessingTime(long minProcessingTime) { this.minProcessingTime = minProcessingTime; }
        public long getMaxProcessingTime() { return maxProcessingTime; }
        public void setMaxProcessingTime(long maxProcessingTime) { this.maxProcessingTime = maxProcessingTime; }
        public long getCount() { return count; }
        public void setCount(long count) { this.count = count; }
        
        public void updateMinMaxTimes(long processingTime) {
            this.minProcessingTime = Math.min(this.minProcessingTime, processingTime);
            this.maxProcessingTime = Math.max(this.maxProcessingTime, processingTime);
            this.count++;
        }
        
        public double getAverageProcessingTime() {
            return count > 0 ? (double) totalProcessingTime / count : 0.0;
        }
        
        public double getAverageDataSize() {
            return count > 0 ? (double) totalDataSize / count : 0.0;
        }
    }

    /**
     * 日报表类
     */
    public static class DailyReport {
        private final Date date;
        private final long processedCount;
        private final long successfulCount;
        private final long failedCount;
        private final long totalDataSize;
        private final long totalProcessingTime;
        private final long generatedTime;

        public DailyReport(Date date, long processedCount, long successfulCount, long failedCount,
                          long totalDataSize, long totalProcessingTime, long generatedTime) {
            this.date = date;
            this.processedCount = processedCount;
            this.successfulCount = successfulCount;
            this.failedCount = failedCount;
            this.totalDataSize = totalDataSize;
            this.totalProcessingTime = totalProcessingTime;
            this.generatedTime = generatedTime;
        }

        // Getter方法
        public Date getDate() { return date; }
        public long getProcessedCount() { return processedCount; }
        public long getSuccessfulCount() { return successfulCount; }
        public long getFailedCount() { return failedCount; }
        public long getTotalDataSize() { return totalDataSize; }
        public long getTotalProcessingTime() { return totalProcessingTime; }
        public long getGeneratedTime() { return generatedTime; }
        
        public double getSuccessRate() {
            return processedCount > 0 ? (double) successfulCount / processedCount : 0.0;
        }
        
        public double getAverageProcessingTime() {
            return processedCount > 0 ? (double) totalProcessingTime / processedCount : 0.0;
        }
    }

    /**
     * 周报表类
     */
    public static class WeeklyReport {
        private final Date weekStartDate;
        private final long processedCount;
        private final long successfulCount;
        private final long failedCount;
        private final long totalDataSize;
        private final long totalProcessingTime;
        private final long generatedTime;

        public WeeklyReport(Date weekStartDate, long processedCount, long successfulCount, long failedCount,
                           long totalDataSize, long totalProcessingTime, long generatedTime) {
            this.weekStartDate = weekStartDate;
            this.processedCount = processedCount;
            this.successfulCount = successfulCount;
            this.failedCount = failedCount;
            this.totalDataSize = totalDataSize;
            this.totalProcessingTime = totalProcessingTime;
            this.generatedTime = generatedTime;
        }

        // Getter方法
        public Date getWeekStartDate() { return weekStartDate; }
        public long getProcessedCount() { return processedCount; }
        public long getSuccessfulCount() { return successfulCount; }
        public long getFailedCount() { return failedCount; }
        public long getTotalDataSize() { return totalDataSize; }
        public long getTotalProcessingTime() { return totalProcessingTime; }
        public long getGeneratedTime() { return generatedTime; }
        
        public double getSuccessRate() {
            return processedCount > 0 ? (double) successfulCount / processedCount : 0.0;
        }
        
        public double getAverageProcessingTime() {
            return processedCount > 0 ? (double) totalProcessingTime / processedCount : 0.0;
        }
    }

    /**
     * 月报表类
     */
    public static class MonthlyReport {
        private final Date month;
        private final long processedCount;
        private final long successfulCount;
        private final long failedCount;
        private final long totalDataSize;
        private final long totalProcessingTime;
        private final long generatedTime;

        public MonthlyReport(Date month, long processedCount, long successfulCount, long failedCount,
                            long totalDataSize, long totalProcessingTime, long generatedTime) {
            this.month = month;
            this.processedCount = processedCount;
            this.successfulCount = successfulCount;
            this.failedCount = failedCount;
            this.totalDataSize = totalDataSize;
            this.totalProcessingTime = totalProcessingTime;
            this.generatedTime = generatedTime;
        }

        // Getter方法
        public Date getMonth() { return month; }
        public long getProcessedCount() { return processedCount; }
        public long getSuccessfulCount() { return successfulCount; }
        public long getFailedCount() { return failedCount; }
        public long getTotalDataSize() { return totalDataSize; }
        public long getTotalProcessingTime() { return totalProcessingTime; }
        public long getGeneratedTime() { return generatedTime; }
        
        public double getSuccessRate() {
            return processedCount > 0 ? (double) successfulCount / processedCount : 0.0;
        }
        
        public double getAverageProcessingTime() {
            return processedCount > 0 ? (double) totalProcessingTime / processedCount : 0.0;
        }
    }

    /**
     * 统计配置类
     */
    public static class StatisticsConfiguration {
        private final boolean statisticsEnabled;
        private final int timeWindowSizeMinutes;
        private final int maxTimeWindows;
        private final int reportGenerationIntervalMinutes;
        private final int dataRetentionDays;
        private final long timestamp;

        public StatisticsConfiguration(boolean statisticsEnabled, int timeWindowSizeMinutes,
                                     int maxTimeWindows, int reportGenerationIntervalMinutes,
                                     int dataRetentionDays, long timestamp) {
            this.statisticsEnabled = statisticsEnabled;
            this.timeWindowSizeMinutes = timeWindowSizeMinutes;
            this.maxTimeWindows = maxTimeWindows;
            this.reportGenerationIntervalMinutes = reportGenerationIntervalMinutes;
            this.dataRetentionDays = dataRetentionDays;
            this.timestamp = timestamp;
        }

        // Getter方法
        public boolean isStatisticsEnabled() { return statisticsEnabled; }
        public int getTimeWindowSizeMinutes() { return timeWindowSizeMinutes; }
        public int getMaxTimeWindows() { return maxTimeWindows; }
        public int getReportGenerationIntervalMinutes() { return reportGenerationIntervalMinutes; }
        public int getDataRetentionDays() { return dataRetentionDays; }
        public long getTimestamp() { return timestamp; }
    }
}
